import { createSlice, createAsyncThunk } from '@reduxjs/toolkit'
import { InitialStateType } from './classify.d'
import axios from 'utils/request'
// api接口
// api/shopList
export const fetchShoplist: any = createAsyncThunk('classify/fetchShoplist', async () => {
  try {
    const response = await axios.get('/api/shopList')
    console.log('response:', response)
    return response
  } catch (err) {
    return Promise.reject(err)
  }
})

const initialState: InitialStateType = {
  list: [],
  total: 0,
  typeObj: {},
  collectArr: [], // 收藏数据
}
const classifySlice = createSlice({
  name: 'classify',
  initialState,
  reducers: {
    set_three_arr(state, action) {
      state.typeObj = state.list[action.payload]
    },
    // 设置收藏数据
    set_collect_arr(state, action) {
      // const collectArr = [action.payload.collect]
      if (action.payload.collect) {
        console.log('action----collect', action.payload)
        //   if (state.collectArr.findIndex((v) => v.id === action.payload.id) === -1) {
        state.collectArr.push(action.payload)
        console.log('state.collectArr:', [...state.collectArr])
      } else {
        state.collectArr.splice(
          state.collectArr.findIndex((v) => v.id === action.payload.id),
          1
        )
      }
    },
  },
  extraReducers: (builder) => {
    builder.addCase(fetchShoplist.fulfilled, (state, action) => {
      state.total = action.payload.data.total
      state.list = action.payload.data.list
    })
  },
})

export default classifySlice.reducer

export const { set_three_arr, set_collect_arr } = classifySlice.actions
